package jjn.round1;

import java.util.*;

/**
 * @author Jiang Jining
 * @since 2023-05-02 23:00
 */
public class LeetCode970_PowerfulIntegers {
    public List<Integer> powerfulIntegers(int x, int y, int bound) {
        Set<Integer> result = new TreeSet<>();
        if (x == 1 || y == 1) {
            if (x == 1 && y == 1) {
                if (x + y <= bound) {
                    result.add(x + y);
                }
            } else {
                int nonOne = (x == 1) ? y : x;
                int maxForY = (int) (Math.log(bound) / Math.log(nonOne));
                for (int i = 0; i <= maxForY; i++) {
                    result.add(1 + (int) Math.pow(nonOne, i));
                }
            }
            return new ArrayList<>(result);
        }
        int maxForX = (int) (Math.log(bound) / Math.log(x));
        int maxForY = (int) (Math.log(bound) / Math.log(y));
        for (int i = 0; i <= maxForX; i++) {
            for (int j = 0; j <= maxForY; j++) {
                int res = (int) (Math.pow(x, i) + Math.pow(y, j));
                if (res <= bound) {
                    result.add(res);
                }
            }
        }
        return new ArrayList<>(result);
    }
    
    public List<Integer> powerfulIntegersV2(int x, int y, int bound) {
        Set<Integer> set = new HashSet<>();
        
        for (int a = 1; a < bound; a *= x) {
            for (int b = 1; a + b <= bound; b *= y) {
                set.add(a + b);
                if (y == 1) {
                    break;
                }
            }
            if (x == 1) {
                break;
            }
        }
        
        return new ArrayList<>(set);
    }
}
